package ruan_kao;

import java.util.*;

abstract class MenuComponent {
    public String name; //1 × protected

    public void printName() {
        System.out.println(name);
    }

    public abstract boolean addMenuElement(MenuComponent element); //2

    public abstract boolean removeMenuElement(MenuComponent element);

    public abstract List<MenuComponent> getElement(); //3
}

class MenuItem extends MenuComponent {
    public MenuItem(String name) {
        this.name = name;
    }

    public boolean addMenuElement(MenuComponent element) {
        return false;
    }

    public boolean removeMenuElement(MenuComponent element) {
        return false;
    }

    public List<MenuComponent> getElement() {
        return null;
    }
}

class Menu extends MenuComponent {
    private List<MenuComponent> elementList; //4

    public Menu(String name) {
        this.name = name;
        this.elementList = new ArrayList<MenuComponent>();
    }

    public boolean addMenuElement(MenuComponent element) {
        return elementList.add(element);
    }

    public boolean removeMenuElement(MenuComponent element) {
        return elementList.remove(element);
    }

    public List<MenuComponent> getElement() {
        return elementList;
    }
}

class CompositeTest {
    public static void main(String[] args) {
        MenuComponent mainMenu = new Menu("Insert");
        MenuComponent subMenu = new Menu("Chart");
        MenuComponent element = new Menu("On This Sheet");
        mainMenu.addMenuElement(subMenu); //5
        subMenu.addMenuElement(element);
        printMenus(mainMenu);
    }

    private static void printMenus(MenuComponent ifile) {
        ifile.printName();
        List<MenuComponent> children = ifile.getElement();
        if (children == null) return;
        for (MenuComponent element : children) {
            printMenus(element);
        }
    }
}
